﻿Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Net.Http
Imports System.Net.Http.Headers
Imports System.Text
Imports System.Threading.Tasks
Imports System.Windows
Imports Newtonsoft.Json

Class FileUploadHttpClient
    Public ReadOnly Property Client As HttpClient

    Private ReadOnly _uploadUrl As String = "vdm/api/file/upload"

    Public Sub New()
        Client = New HttpClient()
        If Application.Current.Resources("Token") IsNot Nothing Then
            Client.DefaultRequestHeaders.Authorization = New AuthenticationHeaderValue("Bearer", Application.Current.Resources("Token").ToString())
        End If
        Client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "multipart/form-data")
        Client.DefaultRequestHeaders.Accept.Clear()
        Client.DefaultRequestHeaders.AcceptCharset.ParseAdd("utf-8")
        Client.DefaultRequestHeaders.Accept.Add(New MediaTypeWithQualityHeaderValue("application/json") With {.CharSet = "utf-8"})
        Client.BaseAddress = New Uri(NavigationData.SERVER_ACCESS_URL, UriKind.Absolute)
        Client.Timeout = TimeSpan.FromSeconds(300)
    End Sub

    Public Async Function UploadFileAsync(file As HttpContent) As Task(Of Result(Of String))
        Dim response = Await Client.PostAsync(_uploadUrl, file)
        If response.IsSuccessStatusCode Then
            Return JsonConvert.DeserializeObject(Of Result(Of String))(Await response.Content.ReadAsStringAsync())
        Else
            Dim errorContent = Await response.Content.ReadAsStringAsync()
            Throw New HttpRequestException($"HTTP {response.StatusCode}: {errorContent}")
        End If
    End Function

End Class
